const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        TotalPrice:0,
        deposit:0,
        order_id: 0,
        order: {},
        user: {},
        pay_type: 1,    //支付类型 1余额 2微信
        coupon_id: 0,   //优惠卷id
        coupon_sub: 0,  // 优惠卷金额
        vip_sub: 0,     //会员折扣
        pay_price: 0,   //支付金额
        rate: 0,    //折扣比例
        store_label:[],
        windowHeight: 654,
        
        clock_time:0,//时间戳
        maxtime: "",
        isHiddenLoading: true,
        isHiddenToast: true,
        dataList: {},
        countDownDay: 0,
        countDownHour: 0,
        countDownMinute: 0,
        countDownSecond: 0,
        //定时器
        payinterval:'',
        fw_status:true,
    },
    pay_success: function () {
        this.payOrder(this.data.pay_type,1);
    },
    account_chongzhi: function () {
        wx.navigateTo({
            url: '/pages/account_chongzhi/account_chongzhi',
        })
    },
    setPayType: function (e) {
        var type = e.currentTarget.dataset.type;
        this.setData({
            pay_type: type
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var order_id = options.order_id || 0,
            user = wx.getStorageSync('user');
            this.data.deposit= wx.getStorageSync('deposit');
        this.setData({
            order_id: order_id,
            user: user,
            TotalPrice:   options.TotalPrice || 0,
            deposit:this.data.deposit || 0,
            
        });
        this.getOrder();
        //每10秒获取订单支付信息
        this.payTiming();
       //倒计时延迟2秒才行 

    },
    goCupon:function(){
        wx.navigateTo({
            url: '/pages/coupon/coupon',
        })
    },
    getOrder: function () {
        app.ajax({
            url: '/api/user/payOrder',
            data: {
                id: this.data.order_id
            },
            success: res => {
                if (res.code == 1) {
                
                    var coupon_id = 0,
                        coupon_sub = 0,
                        vip_sub = 0,
                        pay_price = 0,
                        total_price = parseFloat(res.data.total_price);
                    if (res.data.coupons.length > 0) {
                        coupon_sub = parseFloat(res.data.coupons[0].money);
                        coupon_id = res.data.coupons[0].id;
                    }
                    pay_price = total_price - coupon_sub;
                    var rate = parseFloat(res.data.discount_rate);
                    this.data.coupon_id = coupon_id;
                    this.data.coupon_sub = coupon_sub;
                    this.data.rate = rate;
                    if (rate > 0) {
                        vip_sub = pay_price * (10 - rate) / 10;
                        vip_sub = vip_sub.toFixed(2);
                        vip_sub = parseFloat(vip_sub);
                    }
                    pay_price = pay_price - vip_sub;
                    console.log(res.data.create_time+'clock_time')
                    this.setData({
                        order: res.data,
                        coupon_id: coupon_id,
                        coupon_sub: coupon_sub,
                        vip_sub: vip_sub,
                        pay_price: pay_price,
                        store_label:res.data.label,
                        clock_time:res.data.start,
                    })
                    let that =this
                    setTimeout(()=>{
                      that.countDown();
                  },1000)
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            }
        }, 1);
    },
    //倒计时函数
    countDown:function(){
      //倒计时
     // 1624550400
     var timestamp = Date.parse(new Date());  
     timestamp = timestamp / 1000;  
     console.log("当前时间戳为：" + timestamp);  
      if(this.data.clock_time<=0){
        return
      }
     console.log('clock_time'+this.data.clock_time)
     //var totalSecond = (Date.parse(new Date()) / 1000) - (Date.parse(this.data.clock_time) / 1000) + 2;
     var totalSecond = (Date.parse(new Date()) / 1000) - this.data.clock_time + 2;
     this.interval = setInterval(function () {
        // 秒数
        var second = totalSecond;
        // 天数位
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;
        // 小时位
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;
        // 分钟位
        var min = Math.floor((second - day * 3600 *24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;
        // 秒位
        var sec = second - day * 3600 * 24 - hr * 3600 - min*60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;
        this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
        });
        totalSecond++;
        if (totalSecond < 0) {
        clearInterval(this.interval);
        // wx.showToast({
        //   title: '未开始',
        // });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          fw_status:false
        });
        }
      }.bind(this), 1000);
 },
    //启动定时获取支付信息
    payTiming:function(){
        this.payOrder(1,2);
        this.payinterval = setInterval(function () {
            this.payOrder(1,2);
        }.bind(this), 5000);
   },
   /**                              // operation_type ==2时  pay_type值无效
    * @param {*} pay_type           //支付方式 1余额 2微信
    * @param {*} operation_type     //1支付 2获取账单
    */
   payOrder:function(pay_type,operation_type){
       console.log( this.data.order_id,this.data.coupon_id,pay_type,operation_type,'pay_type,operation_type---------')
        app.ajax({
            url: '/api/user/pay',
            data: {
                order_id: this.data.order_id,
                coupon_id: this.data.coupon_id,
                pay_type: pay_type,
                operation_type:operation_type
            },
            success: res => {
                if (res.code == 1) {
                    if(operation_type == 2){
                        console.log('余额支付operation_type == 2','-------------')
                        var bill_money = res.data.bill_list[0].money; 
                        var pay_price = bill_money - this.data.coupon_sub;
                        var vip_sub = 0;
                        if (this.data.rate > 0) {
                            vip_sub = pay_price * (10 - this.data.rate) / 10;                           
                            vip_sub = vip_sub.toFixed(2);
                            vip_sub = parseFloat(vip_sub);
                        }
                        pay_price = pay_price - vip_sub;
                        var coupon_info = this.data.coupon_sub + vip_sub;
                        this.setData({
                            order_create_time:this.date(this.data.order.create_time),
                            bill_create_time: res.data.bill_data.create_time,
                            bill_hours: res.data.bill_data.hours,
                            // bill_money: res.data.bill_list[0].money,
                            bill_money:this.data.TotalPrice,
                            // pay_price:pay_price,
                            pay_price:this.data.TotalPrice,
                            coupon_info:coupon_info
                        });
                    }else{
                        clearInterval(this.payinterval);
                        console.log('结算页面已关闭');
                        // wx.showToast({
                        //     title: '结算页面已关闭',
                        // });
                        if (res.data && pay_type == 2) {
                            wx.requestPayment({
                                nonceStr: res.data.nonceStr,
                                package: res.data.package,
                                paySign: res.data.paySign,
                                timeStamp: res.data.timeStamp,
                                signType: res.data.signType,
                                success: res => {
                                    console.log(res);
                                    wx.navigateTo({
                                        //url: '/pages/pay_success/pay_success?order_id=' + this.data.order_id
                                        url: '/pages/my_order/my_order'
                                    })
                                }
                            })
                        } else {
                            // wx.navigateTo({
                            //     //url: '/pages/pay_success/pay_success?order_id=' + this.data.order_id
                            //     url: '/pages/my_order/my_order'
                            // })
                            wx.redirectTo({
                                url: '/pages/my_order/my_order'
                            })
                        }
                    }
                } else {
                    //订单已经结束返回首页
                  if(res.data == 100){
                    wx.reLaunch({
                      url: '/pages/index/index'
                  })
                  clearInterval(this.payinterval);
                  }
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                    //console.log(res.msg);
                }
            }
        }, 1);
   },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
       
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(this.payinterval);
        clearInterval(this.interval);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.payinterval);
        clearInterval(this.interval);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    date:function(timestamp) {
	    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	    var Y = date.getFullYear() + '-';
	    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        if(date.getDate() < 10){
            var D = '0' + date.getDate() + ' ';
        }else{
            var D = date.getDate() + ' ';
        }
	    var h = date.getHours() + ':';
        var m = date.getMinutes();
        // var m = date.getMinutes() + ':';
	    // var s = date.getSeconds();
	    return Y + M + D + h + m;
	}
})